<?php
/////////////////////////////////////////////////////////////////////////////
// 
//
// workflow_system 
//
// workflow_copyright
// 
/////////////////////////////////////////////////////////////////////////////

/**
 * FILE_NAME : inifileoperate.class.php   FILE_PATH : \classes\libraries\inifileoperate.class.php
 * 
 * [shopnc]ini文件操作类
 * 举例：
 *      $objini = new IniFileOperate("example.ini");
 *		$configinfosection = $objini->sections();
 *		foreach($configinfosection as $k=>$v){
 *			$iniinfo[$v] = $objini->keys($v);
 *		}
 *		$objini = null;
 *
 * @copyright workflow_system 
 * @author workflow Develop Team 
 * @package 
 * @subpackage 
 * @version Thu Jul 31 10:45:48 CST 2008
 */

class IniFileOperate{
	var $_iniFile;
	/**
	 * 初始化类，设置要读取的INI文件
	 *
	 * @param string $iniFile INI文件
	 */
	function IniFileOperate($iniFile = "") {
        if (!(empty($iniFile))) {
            $this->_iniFile = $iniFile;
        } else {
            die("INI File Required");
        }
    }
    
    /**
     * 去掉INI文件中的注释信息
     *
     * @param int $line 第几行
     * @return string 去掉注释后的内容
     */
    function removecomments($line) {
    	if (strstr($line,'password_write=') && !strstr($line,'## ')){
    		return $line;
    	}
    	if (strstr($line,'username_write=') && !strstr($line,'## ')){
    		return $line;
    	}
        $pos = strpos($line, "#");
        $bFound = true;
        if ($pos === false) 
	        $bFound = false;
        if (!$bFound) {
            $tmpLine = $line;
        } else {
            $tmpLine = rtrim(substr($line, 0, $pos));
        }

        return $tmpLine;
    }
    
    /**
     * 某行是否是区域标志
     *
     * @param int $line 第几行
     * @return boolean
     */
    function issection($line) {
        return (substr($line, 0, 1) == "[");
    }
    
    /**
     * 设置区域关键字的值
     *
     * @param string $section 区域名称
     * @param string $key 关键字名称
     * @param string $value 值
     * @return boolean 是否设置成功
     */
    function setIniFile($section, $key, $value) {
        $found = false;

        if (substr($OS, 0, 3) == "Win") {
            // windows environment
            $newline = "\r\n";
        } else {
            // other environment.  assume *nix
            $newline = "\n";
        }

        // return false if the file does not exist
        if (!(file_exists($this->_iniFile))) {
            return false;
        }

        // read the entire contents of the file into the array
        $arrFile = file($this->_iniFile);

        // open the file for write access deleting all contents
        if (!($fp = @fopen($this->_iniFile, "w")) || !(flock($fp, 6))) {
            return false;
        } else {
            while (list($line_num, $line) = each($arrFile)) {
                $oldLine = trim($line);
                $line = trim($this->removecomments($oldLine));

                fputs($fp, $oldLine.$newline);

                if (strlen($line) > 0 && $line == "[".$section."]") {
                    $found = true;

                    $finished = false;
                    while (!$finished) {
                        if (list($line_num, $line) = each($arrFile)) {
                            $oldLine = trim($line);
                            $line = trim($this->removecomments($oldLine));

                            if (strlen($line) > 0) {
                                if ($this->issection($line)) {
                                    $finished = true;
                                    fputs($fp, $key."=".$value.$newline);
                                    prev($arrFile);
                                } else {
                                    $arrKeyVal = explode("=", $line);
                                    if (trim($arrKeyVal[0]) == $key) {
                                        $finished = true;
                                        fputs($fp, $key."=".$value.$newline);
                                    }
                                }
                            }

                            if (!$finished) {
                                fputs($fp, $oldLine.$newline);
                            }
                        } else {
                            $finished = true;
                            fputs($fp, $key."=".$value.$newline);
                        }
                    }
                }
            }

            if (!$found) {
                fputs($fp, "[".$section."]".$newline);
                fputs($fp, $key."=".$value.$newline);
            }

            flock($fp, 3) || die("Couldn't unlock file: ".$this->_iniFile);

            fclose($fp) || die("Couldn't close file: ".$this->_iniFile);
        }

        return true;
    }
    
    /**
     * 删除一个区域关键字
     *
     * @param string $section 区域名称
     * @param string $key 关键字名
     * @return boolean 是否删除成功
     */
    function deleteKey($section, $key) {
        $found = false;

        if (substr($OS, 0, 3) == "Win") {
            // windows environment
            $newline = "\r\n";
        } else {
            // other environment.  assume *nix
            $newline = "\n";
        }

        // return false if the file does not exist
        if (!(file_exists($this->_iniFile))) {
            return false;
        }

        // read the entire contents of the file into the array
        $arrFile = file($this->_iniFile);

        // open the file for write access deleting all contents
        if (!($fp = @fopen($this->_iniFile, "w")) || !(flock($fp, 6))) {
            return false;
        } else {
            while (list($line_num, $line) = each($arrFile)) {
                $oldLine = trim($line);
                $line = trim($this->removecomments($oldLine));

                fputs($fp, $oldLine.$newline);

                if (strlen($line) > 0 && $line == "[".$section."]") {
                    $found = true;

                    $finished = false;
                    while (!$finished) {
                        if (list($line_num, $line) = each($arrFile)) {
                            $oldLine = trim($line);
                            $line = trim($this->removecomments($oldLine));

                            if (strlen($line) > 0) {
                                if ($this->issection($line)) {
                                    $finished = true;
                                    prev($arrFile);
                                } else {
                                    $arrKeyVal = explode("=", $line);
                                    if (trim($arrKeyVal[0]) == $key) {
                                        $finished = true;
                                    }
                                }
                            }

                            if (!$finished) {
                                fputs($fp, $oldLine.$newline);
                            }
                        } else {
                            $finished = true;
                        }
                    }
                }
            }

            flock($fp, 3) || die("Couldn't unlock file: ".$this->_iniFile);

            fclose($fp) || die("Couldn't close file: ".$this->_iniFile);
        }

        return true;
    }
    
    /**
     * 得到区域关键字的值
     *
     * @param string $section 区域名称
     * @param string $key 关键字名称
     * @param string $default 默认值
     * @return string
     */
    function getIniFile($section, $key, $default) {
        $value = $default;

        // read the entire contents of the file into the array
        if (file_exists($this->_iniFile)) {
            $arrFile = file($this->_iniFile);
        } else {
            $arrFile = array();
        }
        while (list($line_num, $line) = each($arrFile)) {
            $line = $this->removecomments(trim($line));

            if (strlen($line) > 0 && $line == "[".$section."]") {
                $finished = false;

                while (!$finished) {
                    if (list($line_num, $line) = each($arrFile)) {
                        $line = $this->removecomments(trim($line));

                        if ($this->issection($line)) {
                            $finished = true;
                        } else {
                            $arrKeyVal = explode("=", $line, 2);
                            if (trim($arrKeyVal[0]) == $key) {
                                return trim($arrKeyVal[1]);
                            }
                        }
                    } else {
                        $finished = true;
                    }
                }
            }
        }

        return $value;
    }
    
    /**
     * 得到区域列表
     *
     * @return string[]
     */
    function sections() {
        $result = array();

        // read the entire contents of the file into the array
        if (file_exists($this->_iniFile)) {
            $arrFile = file($this->_iniFile);
        } else {
            $arrFile = array();
        }

        $i = 0;
        while (list($line_num, $line) = each($arrFile)) {
            $line = trim($this->removecomments(trim($line)));

            if (strlen($line) > 0 && $this->issection($line)) {
                $result[$i] = substr($line, 1, strlen($line) - 2);
                $i++;
            }
        }

        return $result;
    }
    
    /**
     * 得到区域中的关键字列表
     *
     * @param string $section 区域名称
     * @return string[]
     */
    function keys($section) {
        $keys = array();

        // read the entire contents of the file into the array
        if (file_exists($this->_iniFile)) {
            $arrFile = file($this->_iniFile);
        } else {
            $arrFile = array();
        }

        $i = 0;
        while (list($line_num, $line) = each($arrFile)) {
            $line = $this->removecomments(trim($line));

            if (strlen($line) > 0 && $line == "[".$section."]") {
                $finished = false;

                while (!$finished) {
                    if (list($line_num, $line) = each($arrFile)) {
                        $line = $this->removecomments(trim($line));

                        if ($this->issection($line)) {
                            $finished = true;
                        } else {
                            $arrKeyVal = explode("=", $line);
                            $keys[$arrKeyVal[0]] = $this->getIniFile($section,$arrKeyVal[0],"");
                            $i++;
                        }
                    } else {
                        $finished = true;
                    }
                }
            }
        }

        return $keys;
    }
    
    
     /**
     * 新增区域关键字的值（目前仅适用于位置为配置文件最后的支付方式）
     *
     * @param string $section 区域名称
     * @param string $key 关键字名称
     * @param string $value 值
     * @return boolean 是否设置成功
     */
    function addIniFile($section, $key, $value) {
        $found = false;

        if (substr($OS, 0, 3) == "Win") {
            // windows environment
            $newline = "\r\n";
        } else {
            // other environment.  assume *nix
            $newline = "\n";
        }

        // return false if the file does not exist
        if (!(file_exists($this->_iniFile))) {
            return false;
        }

        // read the entire contents of the file into the array
        $arrFile = file($this->_iniFile);

        // open the file for write access deleting all contents
        if (!($fp = @fopen($this->_iniFile, "w")) || !(flock($fp, 6))) {
            return false;
        } else {
            while (list($line_num, $line) = each($arrFile)) {
            	if (strstr($line,'?>')){
            		$line = $key."=".$value;
            	}
 				
                $oldLine = trim($line);
                $line = trim($this->removecomments($oldLine));
                fputs($fp, $oldLine.$newline);
            }
			fputs($fp, '?>');
			
            flock($fp, 3) || die("Couldn't unlock file: ".$this->_iniFile);

            fclose($fp) || die("Couldn't close file: ".$this->_iniFile);
        }

        return true;
    }
    
    /**
     * 设置数组文件的值
     *
     * @param string $key 关键字名称
     * @param string $value 数组
     * @return boolean 是否设置成功
     */
    function setBaseconfigFile($key, $value) {
        $found = false;

        if (substr($OS, 0, 3) == "Win") {
            // windows environment
            $newline = "\r\n";
        } else {
            // other environment.  assume *nix
            $newline = "\n";
        }

        // return false if the file does not exist
        if (!(file_exists($this->_iniFile))) {
            return false;
        }
        
        // read the entire contents of the file into the array
        $arrFile = file($this->_iniFile);

        // open the file for write access deleting all contents
        if (!($fp = @fopen($this->_iniFile, "w")) || !(flock($fp, 6))) {
            return false;
        } else {
        	$finished = false;
            while (list($line_num, $line) = each($arrFile)) {
                $oldLine = trim($line);
                
                $arrKeyVal = explode(" = ", $oldLine);
                if (trim($arrKeyVal[0]) == '$b_config[\''.$key.'\']') {
                	$finished = true;
                	$split_array = $this->makeLineToArray(trim($arrKeyVal[1]));
                	$line = '$b_config[\''.$key.'\']'.' = array(';
                	/*判断是否已经存在了该名称，如果存在了则替换值，不存在则新增*/
                	if (is_array($value)){
	                	foreach ($value as $k => $v){
	                		$split_array[$k] = $v;
	                	}
                	}
                	if (is_array($split_array)){
                		foreach ($split_array as $k => $v){
                			$line .= "'".$k."'".'=>'."'".$v."',";
                		}
                	}
                	$line .= ');';
                	fputs($fp, $line.$newline);
                }else {
                	if (!$finished && ($oldLine == '?>') ){
		            	$line = '$b_config[\''.$key.'\']'.' = array(';
		            	/*判断是否已经存在了该名称，如果存在了则替换值，不存在则新增*/
		            	if (is_array($value)){
		            		foreach ($value as $k => $v){
		            			$split_array[$k] = $v;
		            		}
		            	}
		            	if (is_array($split_array)){
		            		foreach ($split_array as $k => $v){
		            			$line .= "'".$k."'".'=>'."'".$v."',";
		            		}
		            	}
		            	$line .= ');';
		            	
		            	fputs($fp, $line.$newline);
		            	fputs($fp, '?>'.$newline);
		            }else {
		            	fputs($fp, $oldLine.$newline);
		            }
                }
            }
            

            flock($fp, 3) || die("Couldn't unlock file: ".$this->_iniFile);

            fclose($fp) || die("Couldn't close file: ".$this->_iniFile);
        }

        return true;
    }
    
    /**
     * 将字符串整理为数组格式
     * @author workflow Develop Team    
     * @param  $line 字符串
     * @return array
     */
    function makeLineToArray($line){
    	$line = @substr($line,6,strlen($line));//去除字符串格式的前6个字符'array('
    	$line = @substr($line,0,strlen($line)-3);//去除字符串格式的最后3个字符',);'
    	$line = explode(',',$line);
    	if (is_array($line) && !empty($line)){
    		$array = array();
    		foreach ($line as $k => $v){
    			if ($v != '' && strstr($v,'=>')){
    				$split_line = explode('=>',trim($v));
    				$one = trim(trim($split_line[0]),"'");
    				$two = trim(trim($split_line[1]),"'");
    				$array[$one] = $two;
    			}
    		}
    	}
    	return $array;
    }
    
    
    
    
}
?>